import { Modal, Form, Input, Row, Col, Button } from 'antd';
import React, { useCallback } from 'react';
import { useRequest } from '@umijs/hooks';
import PasswordValidate from '@/components/blocks/PasswordValidate';
import { changePassword } from '@/services/index';
import { aesEncrypt } from '@/config/cryptoService';
import { KAY } from '@/config/api';

const Setting = function Setting(props) {
  const { visible, onClose, onSetSuccess, closable } = props;
  const { getFieldDecorator, validateFields } = props.form;

  const { loading, run } = useRequest(
    ({ password: newPassword, prePasswd: password }) => {
      newPassword = aesEncrypt(newPassword, KAY);
      password = aesEncrypt(password, KAY);
      return changePassword({
        newPassword,
        password,
        userId: localStorage.getItem('id'),
      })
    },
    {
      manual: true,
      onSuccess(data, param) {
        onSetSuccess();
        onClose();
      },
    },
  );

  const onOk = useCallback(() => {
    validateFields().then(run);
  }, [run, validateFields]);

  const formLayout = {
    labelCol: { span: 9 },
    wrapperCol: { span: 15 },
  };

  return (
    <Modal
      visible={visible}
      closable={closable}
      onCancel={onClose}
      maskClosable={closable}
      footer={[
        closable && (
          <Button key="cancel" onClick={onClose}>
            取消
          </Button>
        ),
        <Button key="ok" type="primary" loading={loading} onClick={onOk}>
          保存
        </Button>,
      ]}
      title="密码设置"
      width="40%"
      bodyStyle={{ minHeight: '50vh', display: 'flex', flexDirection: 'column' }}
    >
      <Row justify="center" type="flex" align="middle" style={{ flex: 1 }}>
        <Col>
          {visible && <Form>
            <Form.Item {...formLayout} label="旧密码">
              {getFieldDecorator('prePasswd', {
                rules: [{ required: true, message: '请输入旧密码' }]
              })(<Input.Password size="large" placeholder="请输入旧密码" />)}
            </Form.Item>
            <PasswordValidate {...props} formLayout={formLayout} />
          </Form>}
        </Col>
      </Row>
    </Modal>
  );
};

export default Form.create()(Setting);
